﻿using CommonlyUtils;
using ImModels.Service.Models.Data;
using ImModels.View;
using Snowflake.Core;
using System.Reflection.Emit;

namespace ImClientApi.Utils
{
    /// <summary>
    ///构建器
    /// </summary>
    public class Builder
    {
        private static IdWorker worker = new IdWorker(1, 1);

        /// <summary>
        /// 获取的一个唯一id 雪花ID
        /// </summary>
        /// <returns></returns>
        public static long GetNewSnowId()
        {
            return worker.NextId();
        }

        /// <summary>
        /// 生成秘钥
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string BuilderSearct(EnterpriseRegReq data)
        {
            return Md5Helper.Encrypt(data.ToJson() + DateTime.Now.Ticks);
        }

        /// <summary>
        /// 根据ID获取时间
        /// </summary>
        /// <param name="snowflakeId"></param>
        /// <returns></returns>
        public static DateTime FromSnowId(long snowflakeId)
        {
            // 假设 Snowflake ID 高 41 位是时间戳（相对于纪元时间的毫秒数）
            const long epoch = 1288834974657L;  // Twitter Snowflake 的纪元时间
            const int timestampBits = 41;
            const long maxTimestamp = (1L << timestampBits) - 1;

            // 提取时间戳部分
            long timestamp = (snowflakeId >> 22) & maxTimestamp;

            // 将时间戳转为绝对时间（加上纪元时间）
            var timestamp2 = timestamp + epoch;

            return DateTimeOffset.FromUnixTimeMilliseconds(timestamp2).UtcDateTime.AddHours(8);
        }
    }
}
